'use strict';

const AdminModel = require('../../models/admin/admin')
const userGroupModel = require('../../models/admin/userGroup')
const userGroup_menuModel = require('../../models/menu/userGroup_menu')
const AddressComponent = require('../../prototype/addressComponent')
const crypto = require('crypto')
const formidable = require('formidable')
const dtime = require('time-formater')

class Admin extends AddressComponent {
    constructor() {
        super()
        this.login = this.login.bind(this)
        this.register = this.register.bind(this)
        this.encryption = this.encryption.bind(this)
        this.index = this.index.bind(this)
    }
    //登录
    async login(req, res, next) {
        //通过该方法创建一个form表单
        const form = new formidable.IncomingForm();
        //提交的数据，cb为回调函数
        form.parse(req, async(err, fields, files) => {
            if (err) {
                this.reBody(res)
                return
            }
            const { Username, Password } = fields;
            try {
                if (!Username) {
                    this.reBody(res, 0, 1005, "无效请求参数", '请填写账号！')
                } else if (!Password) {
                    this.reBody(res, 0, 1005, "无效请求参数", '请填写密码！')
                }
            } catch (err) {
                this.reBody(res)
                return
            }
            //初次验证没问题
            //把密码md5
            const newpassword = this.encryption(Password);
            try {
                const admin = await AdminModel.findOne({ Username })
                //给个最低权限
                var x = 10000;
                //最高权限的用户组
                var m = [];
                var k;
                for (var i = 0; i < admin.pid.length; i++) {
                    k = await userGroupModel.findOne({ _id: admin.pid[i] })
                    if (k.levels < x) {
                        x = k.level
                        m = k
                    }
                }
                if (admin.length > 1) {
                    this.reBody(res)
                } else if (!admin) {
                    this.reBody(res, 0, 1005, "无效请求参数", '没有此账号！')
                } else if (newpassword.toString() != admin.Password.toString()) {
                    this.reBody(res, 0, 1005, "无效请求参数", '账号或者密码错误！')
                } else {
                    //用户名，ID，登录时间
                    const now_time = Date.parse(new Date()).toString()
                    //md5
                    const adminToken = this.Md5(admin.Username + admin._id + now_time)
                    const newAdmin = {
                        update_time: now_time,
                        token: adminToken
                    }
                    //存入数据库
                    let bodyD = await AdminModel.update({ _id: admin._id }, { $set: newAdmin }, { upsert: true })


                    if (bodyD) {
                        //返回出去的数据
                        let userobj = new Object();
                        userobj.Username = admin.Username;
                        userobj._id = admin._id;
                        userobj.token = adminToken;
                        userobj.Account = m.Account;
                        userobj.img = admin.img;
                        //获取权限列表
                        this.settoken(req, adminToken)
                        console.log(m)
                        const userGroup_menuData = await userGroup_menuModel.findOne({ userGroup_id: m._id })
                        console.log(userGroup_menuData)
                        let bodydata = {
                            userinfo: userobj,
                            rules: userGroup_menuData.menu_id
                        };

                        console.log(111)
                        this.reBody(res, 0, 1001, "登录成功", bodydata);
                    } else {
                        this.reBody(res);
                    }
                }
            } catch (err) {
                this.reBody(res, 0, 1005, "无效请求参数", '账号或者密码错误！')
            }
        })
    }
    //注册
    async register(req, res, next) {
        const form = new formidable.IncomingForm();
        form.parse(req, async(err, fields, files) => {
            if (err) {
                this.reBody(res)
                return
            }
            const { Username, Password } = fields;
            try {
                if (!Username) {
                    this.reBody(res, 0, 1005, "无效请求参数", '请填写账号！')
                } else if (!Password) {
                    this.reBody(res, 0, 1005, "无效请求参数", '请填写密码！')
                }
            } catch (err) {
                this.reBody(res)
                return
            }
            try {
                const admin = await AdminModel.findOne({ Username })
                if (admin) {
                    this.reBody(res, 0, 1005, "无效请求参数", '该账号已经存在！')
                } else {
                    //开发模式获取最高权限的内容
                    let userGroup = await userGroupModel.findOne()
                    //自增索引
                    const admin_id = await this.getId('admin_id');
                    //md5密码
                    const newpassword = this.encryption(Password);
                    //设置返回的数据
                    const newAdmin = {
                        Username,
                        Account: Username,
                        Password: newpassword,
                        id: admin_id,
                        pid: [userGroup._id],
                        create_time: Date.parse(new Date()).toString(),
                        update_time: Date.parse(new Date()).toString()
                    }
                    await AdminModel.create(newAdmin)
                    //注册成功后给初始权限
                    await this.setPower(userGroup._id, admin_id, 'zhuce')
                    this.reBody(res, 0, 1001, "注册成功", '注册管理员成功！')
                }
            } catch (err) {
                this.reBody(res)
            }
        })
    }
    //将密码打乱后md5
    encryption(password) {
        const newpassword = this.Md5(this.Md5(password).substr(2, 7) + this.Md5(password));
        return newpassword
    }
    //把数值md5
    Md5(password) {
        const md5 = crypto.createHash('md5');
        return md5.update(password).digest('base64');
    }
    //获取所有管理员
    index(req, res, next) {
        const form = new formidable.IncomingForm();
        form.parse(req, async(err, fields, files) => {
            if (err) {
                this.reBody(res)
                return
            }
            const { UserToken } = fields;
            let xtoken = await this.settoken(req, UserToken);
            if (xtoken == 1) {
                //1007表示要重新登录
                this.reBody(res, 0, 1007, "无效请求参数", '无效请求参数！')
            }
            try {
                const adminData = await AdminModel.find().populate('pid').exec()
                this.reBody(res, 0, 1001, "获取成功", adminData)
            } catch (err) {
                this.reBody(res)
            }
        })
    }

}

module.exports = new Admin()